<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2023 yoncron All rights reserved.
// +----------------------------------------------------------------------
// | Author: yoncron <yoncron@163.com>
// +----------------------------------------------------------------------
namespace process;

use app\model\CrontabLogModel;
use app\model\CrontabModel;
use Workerman\Crontab\Parser;
use Workerman\Lib\Timer;

class Crontab
{
    public function onWorkerStart()
    {
        $parser = new Parser();
        $callback = function () use ($parser, &$callback) {
            $crontabLst = CrontabModel::field('crontab_id,rule,callback')->where([['useable','=',1],['deleted','=',0]])->select();
            foreach ($crontabLst as $crontab) {
                $rule = $crontab['rule'];
                $cb = function() use ($crontab){
                    $crontabLogObj = new CrontabLogModel();
                    $crontab['crontab_log_id'] = $crontabLogObj->insertGetId(['crontab_id'=>$crontab['crontab_id'],'start_time'=>time(),'run_status'=>'执行中']);
                    \Webman\RedisQueue\Client::connection('crontab')->send('crontab_queue',$crontab);
                };
                if (!$cb || !$rule) {
                    continue;
                }
                $times = $parser->parse($rule);
                $now = time();
                foreach ($times as $time) {
                    $t = $time-$now;
                    if ($t <= 0) {
                        $t = 0.000001;
                    }
                    Timer::add($t, $cb, null, false);
                }
            }
            Timer::add(60 - time()%60, $callback, null, false);
        };

        $next_time = time()%60;
        if ($next_time == 0) {
            $next_time = 0.00001;
        } else {
            $next_time = 60 - $next_time;
        }
        Timer::add($next_time, $callback, null, false);
    }

}